/*******************************************************************************
 * Copyright (c) 2005, 2014 springside.github.io
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package com.aierkeji.call.cms.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.data.jpa.domain.Specification;

public class DynamicSpecifications {

	@SuppressWarnings("rawtypes")
	public static <T> Specification<T> bySearchFilter(final Collection<SearchFilter> filters, final Class<T> entityClazz) {
		return new Specification<T>() {
			@SuppressWarnings("unchecked")
			@Override
			public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
				if (CollectionUtils.isNotEmpty(filters)) {
//					query.select(root).distinct(true);
					query.distinct(true);
					List<Predicate> predicates = new ArrayList<>();
					for (SearchFilter filter : filters) {
						// nested path translate, 如Task的名为"user.name"的filedName, 转换为Task.user.name属性
						String[] names = StringUtils.split(filter.fieldName, ".");
						Path expression = root.get(names[0]);
						if(!filter.operator.equals(SearchFilter.Operator.JOINEQ)){
							for (int i = 1; i < names.length; i++) {
								expression = expression.get(names[i]);
							}
						}

						Class clz = ReflectionUtils.getFieldType(entityClazz,names[0]);
						Object value = null;
						Class javaType = expression.getJavaType();
						if(java.sql.Timestamp.class.equals(javaType)||java.util.Date.class.equals(javaType)) {
							value = DateTimeUtils.converStrToTimestamp((String)filter.value);
						}else {
							value =  filter.value;
						}
						switch (filter.operator) {
						case JOINEQ:
							if(filter.value.getClass().isArray()){
								String[] array = (String[]) filter.value;
								CriteriaBuilder.In in = builder.in(root.join(names[0]).get(names[1]));
							    for(String s:array){
									in.value(s);
								}
								predicates.add(in);
							}else{
								predicates.add(builder.equal(root.join(names[0]).get(names[1]), filter.value));
							}
							break;
						case EQ:
							if(filter.value.getClass().isArray()){
								String[] array = (String[]) filter.value;
								List<Predicate> pl = new ArrayList<>();
								for(String s:array){
									pl.add(builder.equal(expression, s));
								}
								predicates.add(builder.or(pl.toArray(new Predicate[pl.size()])));
							}else{
								if(clz.equals(Boolean.class)){
									predicates.add(builder.equal(root.get(names[0]).as(clz), Boolean.valueOf(filter.value.toString())));
								}else{
									predicates.add(builder.equal(root.get(names[0]).as(clz), filter.value));
								}

							}
							
							break;
						case LIKE:
							predicates.add(builder.like(expression, "%" + filter.value + "%"));
							break;
						case GT:
							predicates.add(builder.greaterThan(expression, (Comparable) filter.value));
							break;
						case LT:
							predicates.add(builder.lessThan(expression, (Comparable) filter.value));
							break;
						case GTE:
						
							predicates.add(builder.greaterThanOrEqualTo(expression, (Comparable)value));
							break;
						case LTE:
							predicates.add(builder.lessThanOrEqualTo(expression, (Comparable) value));
							break;
						}
					}

					// 将所有条件用 and 联合起来
					if (!predicates.isEmpty()) {
//						query.distinct(true);
						return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
//						return builder.and(predicates.toArray(new Predicate[predicates.size()]));
					}
				}
				return builder.conjunction();
			}
		};
	}
}
